package com.x2.base.consts;

import cn.hutool.core.util.NumberUtil;
import com.x2.base.enums.CommonStatus;
import com.x2.base.sms.AliyunSmsProperties;
import com.x2.core.util.ToolUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import static com.x2.base.consts.ConfigConstant.SYSTEM_CONSTANT_PREFIX;
import static com.x2.core.util.ToolUtil.getTempPath;

/**
 * 系统常量的容器
 *
 * @author x2
 * @Date 2019-06-20 13:37
 */
@Slf4j
public class ConstantsContext {

    private static final String TIPS_END = "，若想忽略此提示，请在开发管理->系统配置->参数配置，设置相关参数！";

    /**
     * 所有的常量，可以增删改查
     */
    private static Map<String, Object> CONSTNTS_HOLDER = new ConcurrentHashMap<>();

    /**
     * 添加系统常量
     */
    public static void putConstant(String key, Object value) {
        if (ToolUtil.isOneEmpty(key, value)) {
            return;
        }
        CONSTNTS_HOLDER.put(key, value);
    }

    /**
     * 删除常量
     */
    public static void deleteConstant(String key) {
        if (ToolUtil.isOneEmpty(key)) {
            return;
        }

        //如果是系统常量
        if (!key.startsWith(SYSTEM_CONSTANT_PREFIX)) {
            CONSTNTS_HOLDER.remove(key);
        }
    }

    /**
     * 获取系统常量
     */
    public static Map<String, Object> getConstntsMap() {
        return CONSTNTS_HOLDER;
    }

    /**
     * 获取验证码开关
     */
    public static Boolean getKaptchaOpen() {
        String gunsKaptchaOpen = (String) CONSTNTS_HOLDER.get("GUNS_KAPTCHA_OPEN");
        if (CommonStatus.ENABLE.getCode().equalsIgnoreCase(gunsKaptchaOpen)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取短信的配置
     */
    public static AliyunSmsProperties getAliyunSmsProperties() {
        String gunsSmsAccessKeyId = (String) CONSTNTS_HOLDER.get("GUNS_SMS_ACCESSKEY_ID");
        String gunsSmsAccessKeySecret = (String) CONSTNTS_HOLDER.get("GUNS_SMS_ACCESSKEY_SECRET");
        String gunsSmsSignName = (String) CONSTNTS_HOLDER.get("GUNS_SMS_SIGN_NAME");
        String gunsSmsLoginTemplateCode = (String) CONSTNTS_HOLDER.get("GUNS_SMS_LOGIN_TEMPLATE_CODE");
        String gunsSmsInvalidateMinutes = (String) CONSTNTS_HOLDER.get("GUNS_SMS_INVALIDATE_MINUTES");

        AliyunSmsProperties aliyunSmsProperties = new AliyunSmsProperties();
        aliyunSmsProperties.setAccessKeyId(gunsSmsAccessKeyId);
        aliyunSmsProperties.setAccessKeySecret(gunsSmsAccessKeySecret);
        aliyunSmsProperties.setSignName(gunsSmsSignName);
        aliyunSmsProperties.setLoginTemplateCode(gunsSmsLoginTemplateCode);
        aliyunSmsProperties.setInvalidateMinutes(Integer.valueOf(gunsSmsInvalidateMinutes));
        return aliyunSmsProperties;
    }

    /**
     * 获取管理系统名称
     */
    public static String getSystemName() {
        String systemName = (String) CONSTNTS_HOLDER.get("GUNS_SYSTEM_NAME");
        if (ToolUtil.isEmpty(systemName)) {
            log.error("系统常量存在空值！常量名称：GUNS_SYSTEM_NAME，采用默认名称：人事管理系统" + TIPS_END);
            return "人事管理系统";
        } else {
            return systemName;
        }
    }

    /**
     * 获取默认密码
     */
    public static String getDefaultPassword() {
        String defaultPassword = (String) CONSTNTS_HOLDER.get("GUNS_DEFAULT_PASSWORD");
        if (ToolUtil.isEmpty(defaultPassword)) {
            log.error("系统常量存在空值！常量名称：GUNS_DEFAULT_PASSWORD，采用默认密码：111111" + TIPS_END);
            return "111111";
        } else {
            return defaultPassword;
        }
    }

    /**
     * 获取管理系统名称
     */
    public static String getOAuth2UserPrefix() {
        String oauth2Prefix = (String) CONSTNTS_HOLDER.get("GUNS_OAUTH2_PREFIX");
        if (ToolUtil.isEmpty(oauth2Prefix)) {
            log.error("系统常量存在空值！常量名称：GUNS_OAUTH2_PREFIX，采用默认值：oauth2" + TIPS_END);
            return "oauth2";
        } else {
            return oauth2Prefix;
        }
    }

    /**
     * 获取顶部导航条是否开启
     */
    public static Boolean getDefaultAdvert() {
        String gunsDefaultAdvert = (String) CONSTNTS_HOLDER.get("GUNS_DEFAULT_ADVERT");
        if (ToolUtil.isEmpty(gunsDefaultAdvert)) {
            log.error("系统常量存在空值！常量名称：GUNS_DEFAULT_ADVERT，采用默认值：true" + TIPS_END);
            return true;
        } else {
            if (CommonStatus.ENABLE.getCode().equalsIgnoreCase(gunsDefaultAdvert)) {
                return true;
            } else {
                return false;
            }
        }
    }

    /**
     * 获取系统发布的版本号（防止css和js的缓存）
     */
    public static String getReleaseVersion() {
        String systemReleaseVersion = (String) CONSTNTS_HOLDER.get("GUNS_SYSTEM_RELEASE_VERSION");
        if (ToolUtil.isEmpty(systemReleaseVersion)) {
            log.error("系统常量存在空值！常量名称：GUNS_SYSTEM_RELEASE_VERSION，采用默认值：guns" + TIPS_END);
            return ToolUtil.getRandomString(8);
        } else {
            return systemReleaseVersion;
        }
    }


    /**
     * 签名图片路径
     *
     * @return 结果
     */
    public static String getSignImagePath() {
        String defaultPath = (String) CONSTNTS_HOLDER.get("SIGN_IMAGE_PATH");
        if (ToolUtil.isNum(defaultPath)) {
            return "/upload/sign";
        }
        return defaultPath;
    }


    /**
     * 获取文件上传路径(用于头像和富文本编辑器)
     */
    public static String getFileUploadPath() {
        String gunsFileUploadPath = (String) CONSTNTS_HOLDER.get("GUNS_FILE_UPLOAD_PATH");
        if (ToolUtil.isEmpty(gunsFileUploadPath)) {
            log.error("系统常量存在空值！常量名称：GUNS_FILE_UPLOAD_PATH，采用默认值：系统tmp目录" + TIPS_END);
            return getTempPath();
        } else {
            //判断有没有结尾符
            if (!gunsFileUploadPath.endsWith(File.separator)) {
                gunsFileUploadPath = gunsFileUploadPath + File.separator;
            }

            //判断目录存不存在
            File file = new File(gunsFileUploadPath);
            if (!file.exists()) {
                boolean mkdirs = file.mkdirs();
                if (mkdirs) {
                    return gunsFileUploadPath;
                } else {
                    log.error("创建tmp目录（" + TIPS_END+"）失败，请重新配置保存目录！");
                    return getTempPath();
                }
            } else {
                return gunsFileUploadPath;
            }
        }
    }

    /**
     * 用于存放bpmn文件
     */
    public static String getBpmnFileUploadPath() {
        String bpmnFileUploadPath = (String) CONSTNTS_HOLDER.get("GUNS_BPMN_FILE_UPLOAD_PATH");
        if (ToolUtil.isEmpty(bpmnFileUploadPath)) {
            log.error("系统常量存在空值！常量名称：GUNS_BPMN_FILE_UPLOAD_PATH，采用默认值：系统tmp目录" + TIPS_END);
            return getTempPath();
        } else {
            //判断有没有结尾符
            if (!bpmnFileUploadPath.endsWith(File.separator)) {
                bpmnFileUploadPath = bpmnFileUploadPath + File.separator;
            }

            //判断目录存不存在
            File file = new File(bpmnFileUploadPath);
            if (!file.exists()) {
                boolean mkdirs = file.mkdirs();
                if (mkdirs) {
                    return bpmnFileUploadPath;
                } else {
                    log.error("系统常量存在空值！常量名称：GUNS_BPMN_FILE_UPLOAD_PATH，采用默认值：系统tmp目录" + TIPS_END);
                    return getTempPath();
                }
            } else {
                return bpmnFileUploadPath;
            }
        }
    }

    /**
     * 获取系统地密钥
     */
    public static String getJwtSecret() {
        String systemReleaseVersion = (String) CONSTNTS_HOLDER.get("GUNS_JWT_SECRET");
        if (ToolUtil.isEmpty(systemReleaseVersion)) {
            String randomSecret = ToolUtil.getRandomString(32);
            CONSTNTS_HOLDER.put("GUNS_JWT_SECRET", randomSecret);
            log.error("jwt密钥存在空值！常量名称：GUNS_JWT_SECRET，采用默认值：随机字符串->" + randomSecret + TIPS_END);
            return randomSecret;
        } else {
            return systemReleaseVersion;
        }
    }

    /**
     * 获取系统地密钥过期时间（单位：秒）
     */
    public static Long getJwtSecretExpireSec() {
        Long defaultSecs = 86400L;
        String systemReleaseVersion = (String) CONSTNTS_HOLDER.get("GUNS_JWT_SECRET_EXPIRE");
        if (ToolUtil.isEmpty(systemReleaseVersion)) {
            log.error("jwt密钥存在空值！常量名称：GUNS_JWT_SECRET_EXPIRE，采用默认值：1天" + TIPS_END);
            CONSTNTS_HOLDER.put("GUNS_JWT_SECRET_EXPIRE", String.valueOf(defaultSecs));
            return defaultSecs;
        } else {
            try {
                return Long.valueOf(systemReleaseVersion);
            } catch (NumberFormatException e) {
                log.error("jwt密钥过期时间不是数字！常量名称：GUNS_JWT_SECRET_EXPIRE，采用默认值：1天" + TIPS_END);
                CONSTNTS_HOLDER.put("GUNS_JWT_SECRET_EXPIRE", String.valueOf(defaultSecs));
                return defaultSecs;
            }
        }
    }

    /**
     * 获取token的header标识
     */
    public static String getTokenHeaderName() {
        String tokenHeaderName = (String) CONSTNTS_HOLDER.get("GUNS_TOKEN_HEADER_NAME");
        if (ToolUtil.isEmpty(tokenHeaderName)) {
            String defaultName = "Authorization";
            CONSTNTS_HOLDER.put("GUNS_TOKEN_HEADER_NAME", defaultName);
            return defaultName;
        } else {
            return tokenHeaderName;
        }
    }

    /**
     * 获取租户是否开启的标识，默认是关的
     */
    public static Boolean getTenantOpen() {
        String tenantOpen = (String) CONSTNTS_HOLDER.get("GUNS_TENANT_OPEN");
        if (ToolUtil.isEmpty(tenantOpen)) {
            log.error("系统常量存在空值！常量名称：GUNS_TENANT_OPEN，采用默认值：DISABLE" + TIPS_END);
            return false;
        } else {
            return CommonStatus.ENABLE.getCode().equalsIgnoreCase(tenantOpen);
        }
    }

    /**
     * 获取默认主页链接
     */
    public static String getIndexDefaultPath() {
        String defaultPath = (String) CONSTNTS_HOLDER.get("GUNS_MENU_DEFAULT_PATH");
        if (ToolUtil.isEmpty(defaultPath)) {
            log.error("系统常量存在空值！常量名称：GUNS_MENU_DEFAULT_PATH，为空串");
            return "";
        } else {
            return defaultPath;
        }
    }


    /**
     * 获取默认部门
     */
    public static Long getDefaultDeptId() {
        String defaultDeptId = (String) CONSTNTS_HOLDER.get("GUNS_DEFAULT_DEPT_ID");
        if (ToolUtil.isEmpty(defaultDeptId)) {
            Long defaultDeptIdL = 999999999999L;
            CONSTNTS_HOLDER.put("GUNS_TOKEN_HEADER_NAME", defaultDeptIdL);
            log.error("获取token的header标识为空！常量名称：GUNS_DEFAULT_DEPT_ID，采用默认值：" + defaultDeptIdL + TIPS_END);
            return defaultDeptIdL;
        } else {
            return NumberUtil.parseLong(defaultDeptId);
        }
    }

    /**
     * 获取默认回调地址
     */
    public static String getArtemisEventCallbackUrl() {
        String defaultPath = (String) CONSTNTS_HOLDER.get("ARTEMIS_EVENT_CALLBACK_URL");
        if (ToolUtil.isEmpty(defaultPath)) {
            log.error("系统常量存在空值！常量名称：ARTEMIS_EVENT_CALLBACK_URL，为空串");
            return "";
        } else {
            return defaultPath;
        }
    }

    /**
     * 获取钉钉的开关
     *
     * @return
     */
    public static boolean getDingtalkOnOff() {
        String defaultPath = (String) CONSTNTS_HOLDER.get("DINGTALK_ONOFF");
        if (ToolUtil.isEmpty(defaultPath)) {
            defaultPath = "关";
        }
        if ("开".equals(defaultPath)) {
            return true;
        }
        return false;
    }

    /**
     * 获取钉钉的appkey
     *
     * @return appkey
     */
    public static String getDingtalkAppkey() {
        String defaultPath = (String) CONSTNTS_HOLDER.get("DINGTALK_APPKEY");
        if (ToolUtil.isEmpty(defaultPath)) {
            log.error("钉钉appkey为null！常量名称：DINGTALK_APPKEY，为空串");
            return "";
        } else {
            return defaultPath;
        }
    }

    /**
     * 获取钉钉的appsecret
     *
     * @return appsecret
     */
    public static String getDingtalkAppSecret() {
        String defaultPath = (String) CONSTNTS_HOLDER.get("DINGTALK_APPSECRET");
        if (ToolUtil.isEmpty(defaultPath)) {
            log.error("钉钉appSecret为null！常量名称：DINGTALK_APPSECRET，为空串");
            return "";
        } else {
            return defaultPath;
        }
    }

    /**
     * 获取移动端 h5钉钉的appsecret
     *
     * @return appsecret
     */
    public static String getAppDingtalkAppSecret() {
        String defaultPath = (String) CONSTNTS_HOLDER.get("APP_DINGTALK_APPSECRET");
        if (ToolUtil.isEmpty(defaultPath)) {
            log.error("钉钉appSecret为null！常量名称：DINGTALK_APPSECRET，为空串");
            return "";
        } else {
            return defaultPath;
        }
    }

    /**
     * 获取移动端 h5钉钉的appkey
     *
     * @return appsecret
     */
    public static String getAppDingtalkAppkey() {
        String defaultPath = (String) CONSTNTS_HOLDER.get("APP_DINGTALK_APPKEY");
        if (ToolUtil.isEmpty(defaultPath)) {
            log.error("钉钉appSecret为null！常量名称：APP_DINGTALK_APPKEY，为空串");
            return "";
        } else {
            return defaultPath;
        }
    }

    /**
     * 获取钉钉的企业CorpID
     *
     * @return corpId
     */
    public static String getDingtalkCorpId() {
        String defaultPath = (String) CONSTNTS_HOLDER.get("DINGTALK_CORPID");
        if (ToolUtil.isEmpty(defaultPath)) {
            return "";
        }
        return defaultPath;
    }

    /**
     * 获取系统域名
     *
     * @return
     */
    public static String getSystemDomainName() {
        String defaultPath = (String) CONSTNTS_HOLDER.get("SYSTEM_DOMAIN_NAME");
        return ToolUtil.isEmpty(defaultPath) ? "" : defaultPath;
    }

    /**
     * 获取钉钉的agentId
     *
     * @return
     */
    public static String getDingtalkAgentId() {
        String defaultPath = (String) CONSTNTS_HOLDER.get("DINGTALK_AGENT_ID");
        return ToolUtil.isEmpty(defaultPath) ? "" : defaultPath;
    }

    /**
     * 获取钉钉的补卡流程code
     *
     * @return appkey
     */
    public static String getReissueCode() {
        String defaultPath = (String) CONSTNTS_HOLDER.get("REISSUE_CODE");
        if (ToolUtil.isEmpty(defaultPath)) {
            log.error("钉钉补卡流程code为null！常量名称：REISSUE_CODE，为空串");
            return "";
        } else {
            return defaultPath;
        }
    }

    /**
     * 获取钉钉的请假流程code
     *
     * @return appkey
     */
    public static String getLeaveCode() {
        String defaultPath = (String) CONSTNTS_HOLDER.get("LEAVE_CODE");
        if (ToolUtil.isEmpty(defaultPath)) {
            log.error("钉钉请假流程code为null！常量名称：REISSUE_CODE，为空串");
            return "";
        } else {
            return defaultPath;
        }
    }

    /**
     * 获取钉钉的加班流程code
     *
     * @return appkey
     */
    public static String getOverTimeCode() {
        String defaultPath = (String) CONSTNTS_HOLDER.get("OVERTIMECODE");
        if (ToolUtil.isEmpty(defaultPath)) {
            log.error("钉钉加班流程code为null！常量名称：REISSUE_CODE，为空串");
            return "";
        } else {
            return defaultPath;
        }
    }

    /**
     * 获取使用第三方插件的配置，如钉钉、微信、企业微信等
     *
     * @return
     */
    public static String getPluginsKey() {
        String defaultPath = (String) CONSTNTS_HOLDER.get("USE_PLUGINS_KEY");
        if (ToolUtil.isEmpty(defaultPath)) {
            log.error("钉钉第三方插件的配置code为null！常量名称：USE_PLUGINS_KEY，为空串");
            return "";
        } else {
            return defaultPath;
        }
    }

    /**
     * 获取使用第三方插件的配置，如钉钉、微信、企业微信等
     *
     * @return
     */
    public static String getContextPath() {
        String defaultPath = (String) CONSTNTS_HOLDER.get("Context_Path");
        if (ToolUtil.isEmpty(defaultPath)) {
            return "";
        } else {
            return defaultPath;
        }
    }

    /**
     * 获取人事部流程提交审批人
     */
    public static String gethrAppUserId() {
        String defaultPath = (String) CONSTNTS_HOLDER.get("HR_APP_USER_ID");
        if (ToolUtil.isEmpty(defaultPath)) {
            log.error("系统常量存在空值！常量名称：HR_APP_USER_ID，为空串");
            return "";
        } else {
            return defaultPath;
        }
    }

    /**
     * 获取人事部部门id
     */
    public static String gethrDeptId() {
        String defaultPath = (String) CONSTNTS_HOLDER.get("HR_DEPT_ID");
        if (ToolUtil.isEmpty(defaultPath)) {
            log.error("系统常量存在空值！常量名称：HR_DEPT_ID，为空串");
            return "";
        } else {
            return defaultPath;
        }
    }

    /**
     * 获取门禁点区域code
     */
    public static String getDoorCode() {
        String defaultPath = (String) CONSTNTS_HOLDER.get("DOOR_CODE");
        if (ToolUtil.isEmpty(defaultPath)) {
            log.error("系统常量存在空值！常量名称：DOOR_CODE，为空串");
            return "";
        } else {
            return defaultPath;
        }
    }

    /**
     * 验证是否开启机构隔离
     *
     * @return true：开启 false：未开启
     */
    public static boolean checkDeptDivide() {
        String value = (String) CONSTNTS_HOLDER.get("SYS_DEPT_DIVIDE_STATUS");
        if (!ToolUtil.isEmpty(value) && "开".equals(value)) {
            return true;
        }
        return false;
    }
}
